import 'dart:async';

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:untitled1/main/privoder/PrivoderMain.dart';

import 'ItemViewCustom.dart';

class HomePage extends StatefulWidget {
  @override
  _homePageState createState() => _homePageState();
}

class _homePageState extends State<HomePage> {
  late PageAState _state;
  var selectIndex = 0;
  List<TestBean> listBeans = [];
  final ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    super.initState();
    _state = Provider.of<PageAState>(context, listen: false);

    if (listBeans.isEmpty) {
      print("initState----------");
      _state.loadData(isRefresh: true);
      // fetchData();
    }
    _scrollController.addListener(() {
      if (_scrollController.position.pixels >= _scrollController.position.maxScrollExtent - 20) {
        if(_state.listBeans.isNotEmpty) _state.loadMore();
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    _scrollController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Android"),
      ),
      body: Consumer<PageAState>(
        builder: (context, state, _) {
          if (state.isLoading && state.listBeans.isEmpty) {
            return Center(child: CircularProgressIndicator());
          }
          return _buildList(state);
        },
      ),
    );
  }

  Widget _buildList(PageAState _state) {
    return Column(
      children: [
        Row(
          children: [
            Container(
                margin: EdgeInsets.fromLTRB(20, 0, 0, 0),
                child: GestureDetector(
                  child: Text("推荐",
                      style: TextStyle(
                          color: _state.selectIndex == 0
                              ? Color(0xFF333333)
                              : Color(0xFF999999))),
                  onTap: () => _state.selectIndex = 0,
                )),
            Container(
                margin: EdgeInsets.fromLTRB(20, 0, 0, 0),
                child: GestureDetector(
                  child: Text(
                    "附近",
                    style: TextStyle(
                        color: _state.selectIndex == 1
                            ? Color(0xFF333333)
                            : Color(0xFF999999)),
                  ),
                  onTap: () => _state.selectIndex = 1,
                )),
            Container(
                margin: EdgeInsets.fromLTRB(20, 0, 0, 0),
                child: GestureDetector(
                  child: Text("最新",
                      style: TextStyle(
                          color: _state.selectIndex == 2
                              ? Color(0xFF333333)
                              : Color(0xFF999999))),
                  onTap: () => _state.selectIndex = 2,
                )),
          ],
        ),
        SizedBox(
          height: 12,
        ),
        Expanded(
          child: RefreshIndicator(
            onRefresh: () => _state.onRefresh(),
            child: ListView.builder(
              controller: _scrollController,
              key: PageStorageKey<String>('list_key'), // 关键：保存滚动状态
              itemCount: _state.listBeans.length + 1, // +1 用于加载更多的指示器
              itemBuilder: (context, index) {
                if (index == _state.listBeans.length) {
                  return _state.isLoading
                      ? Center(child: CircularProgressIndicator())
                      : SizedBox();
                }
                if (_state.listBeans.isEmpty) {
                  return SizedBox();
                }
                return HomeItemView(_state.listBeans[index]);
              },
            ),
          ),
        )
      ],
    );
  }
}

class TestBean {
  final String title;
  final String content;
  final String company;
  final List<String> conditions;

  TestBean(this.title, this.content, this.company, this.conditions);
}

class HomeItemView extends StatefulWidget {
  final TestBean testBean;

  HomeItemView(this.testBean);

  @override
  _HomeItemViewState createState() => _HomeItemViewState();
}

class _HomeItemViewState extends State<HomeItemView> {
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
        child: Container(
          padding: EdgeInsets.fromLTRB(10, 10, 10, 10),
          margin: EdgeInsets.fromLTRB(10, 10, 10, 0),
          decoration: BoxDecoration(
              color: Colors.white, borderRadius: BorderRadius.circular(12)),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _nameAndSize(widget.testBean),
              SizedBox(height: 2),
              Text(widget.testBean.company),
              SizedBox(
                height: 8,
              ),
              _condition(widget.testBean),
              SizedBox(
                height: 8,
              ),
              _bossInfo(widget.testBean)
            ],
          ),
        ),
        onTap: () {
          print("test click");
          Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => JobDetailPage()),
          );
        });
  }
}

Widget _nameAndSize(TestBean testBean) => Row(
      children: [
        Text(testBean.title,
            style: TextStyle(
                color: Color(0xff000000),
                fontSize: 18,
                fontWeight: FontWeight.w600)),
        Expanded(child: Container()),
        Text(testBean.content,
            style: TextStyle(
                color: Colors.green, fontSize: 18, fontWeight: FontWeight.w500))
      ],
    );

Widget _condition(TestBean testBean) => Wrap(
      children: testBean.conditions
          .map((item) => Container(
                padding: EdgeInsets.fromLTRB(8, 4, 8, 4),
                margin: EdgeInsets.fromLTRB(2, 0, 2, 0),
                color: Color(0xfff5f5f5),
                child: Text(item),
              ))
          .toList(),
    );

Widget _bossInfo(TestBean testBean) => Row(
      children: [
        Icon(Icons.school_outlined),
        SizedBox(width: 2),
        Padding(
          padding: EdgeInsets.only(left: 4), // 统一设置左边距
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                "Sir - CEO",
                style: TextStyle(color: Color(0xff333333), fontSize: 14),
              ),
              SizedBox(height: 2),
              Text("今日回复9次",
                  style: TextStyle(color: Color(0xff999999), fontSize: 12))
            ],
          ),
        ),
        Expanded(child: Container()),
        Text(
          "相城区 开发区",
          style: TextStyle(fontSize: 14, color: Color(0xff999999)),
        ),
        SizedBox(
          width: 4,
        ),
        Icon(
          Icons.close,
          color: Color(0x80000000),
        )
      ],
    );
